package cn.zebra.dev.shop.module.delivery.service.impl;

import cn.zebra.dev.ibatis.plus.service.impl.ServiceImpl;
import cn.zebra.dev.shop.module.delivery.dao.DeliveryItemDao;
import cn.zebra.dev.shop.module.delivery.entity.DeliveryItemEntity;
import cn.zebra.dev.shop.module.delivery.service.DeliveryItemService;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Future;

/**
 * 运费模板(子表)
 *
 * @author runnable
 */
@Service
public class DeliveryItemServiceImpl extends ServiceImpl<DeliveryItemDao, DeliveryItemEntity> implements DeliveryItemService {
    @SneakyThrows
    @Override
    public boolean saveBatch(Collection<DeliveryItemEntity> entityList) {
        if (entityList != null && entityList.size() > 0) {
            List<Future<Boolean>> list = new ArrayList<>(entityList.size());
            entityList.forEach(entity -> list.add(this.asyncSave(entity)));
            for (int i = list.size() - 1; i >= 0; i--) {
                if (!list.get(i).get()) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    @Override
    @Async
    public Future<Boolean> asyncSave(DeliveryItemEntity entity) {
        return AsyncResult.forValue(this.save(entity));
    }

    @Override
    public boolean save(DeliveryItemEntity entity) {
        Collection<Long> cityIds = entity.getCityIds();
        if (cityIds == null) {
            cityIds = new ArrayList<>();
        }
        entity.setCityIdArrayJson(JSON.toJSONString(cityIds));
        return super.save(entity);
    }

    @Override
    @SneakyThrows
    public boolean updateBatch(Collection<DeliveryItemEntity> entityList) {
        if (entityList != null && entityList.size() > 0) {
            List<Future<Boolean>> list = new ArrayList<>(entityList.size());
            entityList.forEach(entity -> list.add(this.asyncUpdate(entity)));
            for (int i = list.size() - 1; i >= 0; i--) {
                if (!list.get(i).get()) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    @Async
    public Future<Boolean> asyncUpdate(DeliveryItemEntity entity) {
        return AsyncResult.forValue(this.update(entity, "id = {0}", entity.getId()));
    }
}
